﻿/* 
 * This file is part of the Coffee Survey Framework - http://coffee.codeplex.com
 */
using System.Linq;
using System.Reflection;

namespace Coffee.Utils
{
    public static class ObjectExtensions
    {
        public static void CopyTo(this object from, object to)
        {
            CopyTo(from, to, null);
        }

        public delegate bool PropertyMapperDelegate(PropertyInfo fromproperty, PropertyInfo toproperty, object from, object to);

        public static void CopyTo(this object from, object to, PropertyMapperDelegate mapper)
        {
            var t = from.GetType();
            var p = to.GetType().GetProperties();

            foreach (var Property in t.GetProperties())
            {
                var q = p.Where(n => n.Name == Property.Name).FirstOrDefault();

                if (q != null)
                {
                    bool mapped = false;
                    
                    if (mapper != null)
                        mapped = mapper(Property, q, from, to);
                    
                    if (!mapped)
                    {
                        if (q.CanWrite)
                        {
                            q.SetValue(to, Property.GetValue(from, null), null);
                        }
                    }
                }
            }

        }

    }
}
